package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baidubce.qianfan.util.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.message.IotMsgNotifyData;
import com.zzyl.nursing.message.IotMsgService;
import com.zzyl.nursing.service.IDeviceDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {

    private final DeviceMapper deviceMapper;
    private final RedisTemplate<String,String> redisTemplate;

    @Override
    public void saveData(IotMsgNotifyData iotMsgNotifyData) {
        log.info("将设备的数据保存");
        // 1. 判断设备是否存在
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        // 查询设备
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,deviceId));
        if (device == null) {
            new BaseException("设备不存在");
        }
        // 2. 获取相应的数据 创建对象，将数据存入对象
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        // 批量插入的数据属性集合
        List<DeviceData> deviceData = new ArrayList<>();
        for (IotMsgService service : services) {
            //获取属性
            Map<String, Object> properties = service.getProperties();
            //获取时间
            String eventTime = service.getEventTime();
            LocalDateTime parse = LocalDateTimeUtil.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'hhmmss'Z'"));
            //时区转换
            LocalDateTime zoneTime = parse.atZone(ZoneId.from(ZoneOffset.UTC)).
                    withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            //循环存入属性
            properties.forEach((key,value) ->{
                //数据
                DeviceData data = new DeviceData();
                BeanUtils.copyProperties(device,data);
                data.setId(null);
                data.setFunctionId(key);
                data.setDataValue(value + "");
                data.setAlarmTime(zoneTime);
                //存入集合
                deviceData.add(data);
            });
        }
        // 3. 存入数据库
        super.saveBatch(deviceData);
        // 存入redis 最新的数据
        redisTemplate.opsForHash().put("DEVICE_NEW_DATA", deviceId, JSONUtil.toJsonStr(deviceData));
    }

    /**
     * 查询设备数据列表
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto){
        Page<DeviceData> page = new Page(dto.getPageNum(),dto.getPageSize());
        LambdaQueryWrapper<DeviceData> wrapper = Wrappers.<DeviceData>lambdaQuery().like(DeviceData::getDeviceName, dto.getDeviceName())
                .eq(DeviceData::getIotId, dto.getDeviceId())
                .ge(DeviceData::getAlarmTime, dto.getStartTime())
                .le(DeviceData::getAlarmTime, dto.getEndTime());
        page = page(page,wrapper);
        //封装分页对象
        return getTableDataInfo(page);
    }

    /**
     * 封装分页对象
     * @param page
     * @return
     */
    @NotNull
    private static TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }
}
